package com.example.captchademo.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.example.captchademo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties properties;
    @RequestMapping("/get")
    public void getCaprcha(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(properties.getWidth(), properties.getHeight(), 4, 4);
        //设置返回类型
        response.setContentType("image/jpeg");
        //禁止缓存
        response.setHeader("Progma","No-cache");
        //ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
         //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(response.getOutputStream());
        //存储session
        session.setAttribute(properties.getSession().getKey(),captcha.getCode());
        session.setAttribute(properties.getSession().getDate(),new Date());
        response.getOutputStream().close();
    }

    @RequestMapping("/check")
    public Boolean check(String inputCode,HttpSession session){
        //验证码生成的内容和用户输入进行比较
        //从session获取信息
        String captchaSessionKey = (String) session.getAttribute(properties.getSession().getKey());
        if (!StringUtils.hasLength(captchaSessionKey)||!StringUtils.hasLength(inputCode)){
            return false;
        }
        if(!captchaSessionKey.equalsIgnoreCase(inputCode)){
            return false;
        }
        //验证码是否过期
        Date saveDate = (Date) session.getAttribute(properties.getSession().getDate());
        Date curDate = new Date();
        if (saveDate == null || (curDate.getTime()-saveDate.getTime()) >= properties.getSession().getTime_out()) {
                    return false;
        }
        return true;
    }
}
